import React, { useState, useEffect, useImperativeHandle } from 'react';
import { Button, Icon, message, Upload, Progress } from 'antd';
import COMMONATION from 'service/apis/commonAction';
import { connect } from 'dva';
import pic from 'dic/pic';
import upload from 'assets/ledger/upload.png';
import AWS from 'aws-sdk'
import { v4 as uuid } from 'uuid'
import './index.styl';

/*
 * 图片 文档 pdf上传组件
 */
function UploadPanel({
  cRef,
  dispatch,
  commonAction: { uploadInfo },
  getFileList,
  editFileList,
  isNone,
  actionType,
  num,
  mb,
  uploadNum,
  flag,
  id,
  tip,
  getFileName
}) {
  const [fileLists, setFileList] = useState([]);
  const [fileName, setFileName] = useState([]);
  const [picObj] = useState(pic.obj);
  const [uploadError, setUploadError] = useState(false);
  const [fileSizeError, setFileSizeError] = useState(false);
  useImperativeHandle(cRef, () => ({
    fileLists,
    fileName
  }));
  useEffect(() => {
    dispatch({
      type: 'commonAction/getToken',
    });
  }, [dispatch]);

  useEffect(() => {
    if (actionType === 'edit') {
      setFileName([])
      setFileList(editFileList)
    }
  }, [actionType, editFileList])
  useEffect(() => {
    if (id !== undefined) {
      setFileName([])
      setFileList([])
    }
  }, [id])
  useEffect(() => {
    if (uploadError) {
      message.error('上传失败', 2, () => {
        setUploadError(false)
      });
    }
  }, [uploadError])
  useEffect(() => {
    if (fileSizeError) {
      message.error(`文件要不大于${mb}MB!`, 2, () => {
        setFileSizeError(false)
      });
    }
  }, [fileSizeError, mb])
  const [fileNumError, setFileNumError] = useState(false)
  useEffect(() => {
    if (fileNumError) {
      message.error(`文件个数不超过${num}个`, 2, () => {
        setFileNumError(false)
      });
    }
  }, [fileNumError, num])
  const arr = []
  const props = {
    name: 'file',
    accept: ".jpg,.png,.jpeg,.doc,.docx,.pdf",
    multiple: true,
    action: COMMONATION.UPLOAD_IMG,
    headers: {
      authorization: 'Bearer ' + uploadInfo.token,
    },
    showUploadList: false,
    beforeUpload(value) {
      flag++;
      uploadNum(flag)
      const { size, name, uid } = value;
      const isLt50M = size / 1024 / 1024 <= mb;
      if (flag > num || (flag + fileLists.length) > num) {
        setFileNumError(true)
        flag--;
        uploadNum(flag)
        return false
      }
      if (!isLt50M) {
        setFileSizeError(true)
        flag--;
        uploadNum(flag)
        return false
      }
      if (isLt50M && (flag <= num) && ((flag + fileLists.length) <= num)) {
        arr.push({ name, uid, percent: 0 })
        setFileName([...fileName, ...arr]);
        getFileName && getFileName([...fileName, ...arr])
      }
      return true
    },
    onChange(info) {
      const {
        event,
        file: { status, uid }
      } = info;
      if (status === 'uploading') {
        if (event) {
          const percent = event.percent;
          setFileName([...fileName.map(item => {
            if (item.uid === uid) {
              item.percent = percent
            }
            return item
          })])
        }
      }
      if (status === 'done') {
        const newArr = fileName.map(item => {
          if (item.uid === uid) {
            item.show = true
          }
          return item
        })
        setFileName([...newArr])
        getFileName && getFileName([...newArr])
        const { file } = info
        const uid2 = file.uid
        const { type } = file
        file.typeCode = pic.typeCode[type];
        if (!(fileName.find(item => item.uid === uid2))) {
          return
        }
        flag--;
        uploadNum(flag)
        setFileList([...fileLists, file])
        getFileList([...fileLists, file])
      } else if (info.file.status === 'error') {
        const newArr = fileName.map(item => {
          if (item.uid === uid) {
            item.show = true
          }
          return item
        })
        flag--;
        uploadNum(flag)
        setFileName([...newArr])
        getFileName && getFileName([...newArr])
        const { file } = info
        const uid2 = file.uid
        if (!(fileName.find(item => item.uid === uid2))) {
          return
        }
        setUploadError(true)
      }
    },
  };

  const awsProps = {
    showUploadList: false,
    multiple: true,
    accept: ".jpg,.png,.jpeg,.doc,.docx,.pdf",
    beforeUpload(value) {
      flag++;
      uploadNum(flag)
      const { size, name, uid } = value;
      const isLt50M = size / 1024 / 1024 <= mb;
      if (flag > num || (flag + fileLists.length) > num) {
        setFileNumError(true)
        flag--;
        uploadNum(flag)
        return false
      }
      if (!isLt50M) {
        setFileSizeError(true)
        flag--;
        uploadNum(flag)
        return false
      }
      if (isLt50M && (flag <= num) && ((flag + fileLists.length) <= num)) {
        arr.push({ name, uid, percent: 0 })
        setFileName([...fileName, ...arr]);
      }
      return true
    },
    onChange(info) {
      const {
        event,
        file: { status, name, originFileObj, uid },
      } = info;
      if (status === 'uploading') {
        if (event) {
          const percent = event.percent;
          setFileName([...fileName.map(item => {
            if (item.name === name) {
              item.percent = percent
            }
            return item
          })])
        }
      }
      if (status === 'done') {
        AWS.config.endpoint = 'https://oss-cn-north-2.unicloudsrv.com'
        AWS.config.region = "cn-beijing-1"
        AWS.config.accessKeyId = uploadInfo.accessKeyId
        AWS.config.secretAccessKey = uploadInfo.secretAccessKey
        AWS.config.sessionToken = uploadInfo.token
        AWS.config.s3ForcePathStyle = true
        const s3 = new AWS.S3()
        const _fileName = uuid() + pic.matchObj[originFileObj.type]
        s3.putObject({
          Bucket: 'chengdufensuo',
          Key: _fileName,
          Body: originFileObj
        }, (err, data) => {
          if (err) {
            message.error(`上传失败`);
          } else {
            const newArr = fileName.map(item => {
              if (item.uid === uid) {
                item.show = true
              }
              return item
            })
            setFileName([...newArr])
            const { file } = info
            const uid2 = file.uid
            const { type } = file
            file.typeCode = pic.typeCode[type];
            file.fileUrl = `https://chengdufensuo.oss-cn-north-2.unicloudsrv.com/${_fileName}`
            if (!(fileName.find(item => item.uid === uid2))) {
              return
            }
            flag--;
            uploadNum(flag)
            setFileList([...fileLists, file]);
            getFileList([...fileLists, file]);
          }
        })
      } else if (status === 'error') {
        const { file } = info
        const uid2 = file.uid
        if (!(fileName.find(item => item.uid === uid2))) {
          return
        }
        flag--;
        uploadNum(flag)
        setUploadError(true)
      }
    },
  };

  // 删除文件
  const deleteFile = value => {
    const { uid } = value;
    fileLists.map((item, index) => {
      if (item.uid === uid) {
        fileLists.splice(index, 1);
      }
    });
    getFileList(fileLists);
    setFileList([...fileLists]); // 防止潜复制
  };
  const propsData = uploadInfo.fileService === "Local" ? props : awsProps
  return (
    <div className="UploadPanel" style={{ display: isNone ? 'block' : 'none' }}>
      <div className="flexWrapper" style={{ display: isNone ? 'block' : 'none' }}>
        <div>
          <Upload {...propsData} >
            <Button className={["btn fix-btn", ((fileLists.length === num) || ((fileLists.length + fileName.filter(item => item.show === undefined).length) >= num)) ? "disabled-btn" : null].join(' ')} disabled={((fileLists.length === num) || ((fileLists.length + flag) >= num)) ? true : false}>
              <Icon type="upload" /> 上传
            </Button>
          </Upload>
        </div>
        <div>
          <div>{`1.请上传${tip}，支持格式：doc、docx、pdf、jpg、jpeg、png。`}</div>
          <div>2.最多可上传{num}个文件，单个文件不大于{mb}M</div>
        </div>
      </div>

      <div className="fileWrapper">

        <div className='itembox'>
          {/* {fileName && isShow ? (
            fileName.map((i) => {
              return (
                <div className="uploading" key={i + uuid()}>
                  <div>
                    <img src={upload} alt="" />
                  </div>
                  <div className="upload-pro">
                    {i}（{percent === 100 ? '上传成功' : '上传中'}）
                    <Progress percent={percent || 0} showInfo={false} />
                  </div>
                </div>
              )
            })
          ) : null} */}
          {
            fileName.length > 0 && fileName.map(item => {
              if (item.percent === 100 && item.show) {
                return null
              }
              return (
                <div className="uploading" key={uuid()}>
                  <div>
                    <img src={upload} alt="" />
                  </div>
                  <div className="upload-pro">
                    <div>
                      <span style={{
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        width: '70px',
                        display: 'inline-block',
                        position: 'relative',
                        top: '6px'
                      }}>{item.name}</span>
                      <span>
                      （{item.percent === 100 && item.show ? '上传成功' : '上传中'}）
                      </span>
                    </div>
                    <Progress percent={item.percent || 0} showInfo={false} />
                  </div>
                </div>
              )
            })
          }
          {fileLists.length > 0 &&
            fileLists.map((item, index) => {
              return (
                <div className="item" key={'x' + index}>
                  <div className='imgs'>
                    <img
                      src={
                        picObj[item.type] ||
                        picObj[item.fileUrl.split('.')[item.fileUrl.split('.').length - 1]]
                      }
                      alt={''}
                    />
                  </div>
                  <div className="name">{item.name || item.fileName}</div>
                  <div className="icon">
                    <Icon type="close" onClick={() => deleteFile(item)} style={{ fontSize: '0.14rem' }} />
                  </div>
                </div>
              );
            })}
        </div>
      </div>
    </div>
  );
}

export default connect(({ commonAction }) => ({
  commonAction,
}))(UploadPanel);
